<template>
  <div class="chat-container">
    <div class="sidebar" :style="{ width: isCollapsed ? '0' : '350px' }">
      <!-- 侧边栏内容 -->
      <div class="sidebar-header">
        <el-button size="large" @click="createNewChat">
          <el-icon>
            <Plus />
          </el-icon>
          <span>创建新对话</span>
        </el-button>
      </div>

      <div class="sidebar-main">
        <h3 class="history-title">历史对话</h3>
        <div v-for="chat in chatList" :key="chat.id" class="chat-item" :class="{ active: chat.active }"
          :style="{ backgroundColor: chat.active ? '#3e3e3e' : '#4a4a4a1a' }" @click="setActiveChat(chat)">
          <el-icon class="icon" @click="editChatTitle(chat)">
            <Edit />
          </el-icon>
          <el-icon class="icon" @click="deleteChat(chat)">
            <Delete />
          </el-icon>
          <span v-if="!chat.editing">{{ chat.title }}</span>
          <input v-if="chat.editing" v-model="chat.tempTitle" @keyup.enter="saveChatTitle(chat)"
            @blur="saveChatTitle(chat)" class="edit-input">
        </div>
      </div>
    </div>

    <div class="main-content" :style="{ marginLeft: isCollapsed ? '0' : '350px' }">
      <div class="toggle-btn" @click="toggleCollapse">
        <el-icon :size="20">
          <ArrowLeft v-if="!isCollapsed" />
          <ArrowRight v-else />
        </el-icon>
      </div>

      <div class="message-list" ref="messageListRef">
        <div v-for="(message, index) in messages" :key="index" class="message">
          <div class="message-content" :class="{ 'self': message.isSelf, 'system': message.isSystem }">
            <template v-if="message.hasThink">
              <div v-if="message.showThink" class="think-content">
                <div class="think-header">
                  <span>思考过程</span>
                  <el-button size="small" @click="message.showThink = false">隐藏</el-button>
                </div>
                <div class="think-body">{{ message.thinkContent }}</div>
              </div>
              <div v-else class="think-collapsed">
                <el-button size="small" @click="message.showThink = true">查看思考过程</el-button>
              </div>
              <div class="response-content">{{ message.text.replace(/<think>[\s\S]*?<\/think>/, '') }}</div>
            </template>
            <template v-else>
              {{ message.text }}
            </template>
          </div>
          <div class="message-time">
            {{ message.time }}
          </div>
        </div>
      </div>
      <div class="input-area">
        <el-input v-model="newMessage" @keyup.enter="handleKeyup" type="textarea" placeholder="输入消息..."
          class="input-box" :autosize="{ minRows: 4, maxRows: 6 }" />
        <button @click="sendMessage" class="send-btn">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'
import { ArrowLeft, ArrowRight, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'
import { streamChat } from '@/api/chat'

const isCollapsed = ref(false)
const chatList = ref([
  { id: 1, title: 'New Chat', active: true }
])
const messages = ref([
  { text: '欢迎使用智能聊天系统。你好，有什么可以帮您？', isSelf: false, isSystem: true, time: new Date().toLocaleTimeString() },
])
const newMessage = ref('')

const handleKeyup = (e) => {
  if (e.shiftKey && e.key === 'Enter') {
    e.preventDefault()
  } else if (e.key === 'Enter') {
    sendMessage()
  }
}

const sendMessage = async () => {
  const message = newMessage.value.trim()
  if (!message) return
  
  // 添加用户消息
  messages.value.push({
    text: message,
    isSelf: true,
    time: new Date().toLocaleTimeString()
  })
  newMessage.value = ''

  try {
    // 创建AI回复占位消息
    messages.value.push({
      text: '思考中...',
      isSelf: false,
      isSystem: false,
      time: new Date().toLocaleTimeString()
    })
    
    const response = await streamChat(message)
    await processStreamResponse(response)
  } catch (error) {
    // 错误处理保持不变
    console.error('请求失败:', error)
    messages.value.push({
      text: '请求失败，请检查网络连接',
      isSelf: false,
      isSystem: true,
      time: new Date().toLocaleTimeString()
    })
  }
}

const createNewChat = () => {
  chatList.value.forEach(chat => chat.active = false)
  chatList.value.unshift({
    id: Date.now(),
    title: 'New Chat',
    active: true
  })
}

const messageListRef = ref(null)
const isNearBottom = ref(true)

const checkScrollPosition = () => {
  if (messageListRef.value) {
    const { scrollTop, scrollHeight, clientHeight } = messageListRef.value
    isNearBottom.value = scrollHeight - (scrollTop + clientHeight) < 50
  }
}

const scrollToBottom = debounce(() => {
  if (!isNearBottom.value) return
  
  nextTick(() => {
    if (messageListRef.value) {
      messageListRef.value.scrollTo({
        top: messageListRef.value.scrollHeight,
        behavior: 'smooth' // 添加平滑滚动
      })
    }
  })
}, 100)

// Watch messages changes
watch(messages, () => {
  scrollToBottom()
}, { deep: true })

// Lifecycle hooks
onMounted(() => {
  scrollToBottom()
  if (messageListRef.value) {
    messageListRef.value.addEventListener('scroll', checkScrollPosition)
  }
})

onBeforeUnmount(() => {
  if (messageListRef.value) {
    messageListRef.value.removeEventListener('scroll', checkScrollPosition)
  }
})

const processStreamResponse = async (response) => {
  const reader = response.body.getReader()
  const decoder = new TextDecoder()
  let done = false
  let fullText = ''
  
  while (!done) {
    const { value, done: streamDone } = await reader.read()
    done = streamDone
    if (value) {
      const chunk = decoder.decode(value)
      fullText += chunk
      
      // 更新最后一条消息内容
      if (messages.value.length > 0) {
        const lastMessage = messages.value[messages.value.length - 1]
        if (!lastMessage.isSelf) {
          // 解析think标签内容
          const thinkMatch = fullText.match(/<think>([\s\S]*?)<\/think>/)
          lastMessage.text = fullText
          lastMessage.hasThink = !!thinkMatch
          lastMessage.thinkContent = thinkMatch ? thinkMatch[1] : ''
          lastMessage.showThink = false
          
          messages.value = [...messages.value]
        }
      }
    }
  }
  return fullText
}
</script>

<style scoped>
.chat-container {
  position: relative;
  display: flex;
  height: 100vh;
  overflow: hidden;
}
.sidebar {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 350px;
  background: #f5f7fa;
  border-right: 1px solid #e4e7ed;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  z-index: 1;
}

.main-content {
  flex: 1;
  transition: margin 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.toggle-btn {
  position: absolute;
  top: 50%;
  /* left: 5px; */
  transform: translateX(-50%) translateY(-50%);
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 50%;
  padding: 8px;
  cursor: pointer;
  transition: all 0.3s;
  z-index: 3;
}

.toggle-btn:hover {
  background: #f5f7fa;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.toggle-btn .el-icon {
  display: block;
  color: #606266;
  margin-left: 10px;
}

.sidebar-header {
  height: 116px;
  border: 1px solid #e0e0e6;
  border-left: unset;
  display: flex;
  /* 水平居中 */
  justify-content: center;
  align-items: center;
}

.sidebar-main {
  height: calc(100% - 116px);
  border: 1px solid #e0e0e6;
  border-left: unset;
  padding: 16px;
  /* border-radius: 8px; */
  overflow-y: auto;
}

.history-title {
  margin-bottom: 16px;
  font-weight: 500;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  margin-bottom: 8px;
  border-radius: 4px;
  color: #fff;
  transition: background-color 0.5s;
  background-color: #4a4a4a;
}

.chat-item.active {
  background-color: #3e3e3e;
  position: relative;
}

.message-list {
  flex: 1;
  padding: 20px 40px;
  overflow-y: auto;
  scroll-behavior: smooth;
}

.input-area {
  display: flex;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #e4e7ed;
  background: white;
  z-index: 1000;
  margin: 0 40px 20px; /* 添加左右边距 */
}
</style>

<style scoped>
.message-list {
  flex: 1;
  padding: 40px;
  overflow-y: auto;
  scroll-behavior: smooth;
  height: calc(100vh - 200px); /* 添加固定高度 */
  padding-bottom: 80px; /* 增加底部内边距 */
}

.message {
  margin-bottom: 16px;
  word-break: break-word; /* 添加自动换行 */
}

.message-content {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 12px;
  white-space: pre-wrap;
}

/* 接收的消息样式 */
.message-content:not(.self) {
  background: #f0f0f0;
  margin-right: auto;
  border-top-left-radius: 0;
}

/* 发送的消息样式 */
.message-content.self {
  background: #409eff;
  color: white;
  margin-left: auto;
  border-top-right-radius: 0;
}

/* 系统消息样式 */
.message-content.system {
  background: #e6f7ff;
  color: #333;
  margin: 0 auto;
  text-align: center;
  border-radius: 12px;
}
</style>

<style scoped>
.think-content {
  background: #f8f8f8;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 8px;
}

.think-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.think-body {
  white-space: pre-wrap;
  color: #666;
}

.think-collapsed {
  margin-bottom: 8px;
}

.response-content {
  margin-top: 8px;
}
</style>
